<?php

use console\db\Migration;
use common\helpers\StringHelper;
use yii\db\Query;

/**
 * 用户认证信息转移
 * 
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class m300000_000011_t_user_authent_log extends Migration {

    /**
     * @inheritdoc
     */
    public $tableName = '{{%user_authent}}';

    /**
     * @inheritdoc
     */
    public function safeUp() {
        $query = (new Query())->from($this->tableName)->andWhere([
            'and',
            ['IS NOT', 'mark', null],
            ['!=', 'mark', '']
        ]);
        $this->handleProgress($query, [$this, 'evenDule']);
    }

    /**
     * 处理结果
     * @param Migration $migration
     * @param array $rows
     */
    public static function evenDule($migration, $rows) {
        if (empty($rows)) {
            return;
        }
        $connect = $migration->db->createCommand();
        $items = [];
        foreach ($rows as $row) {
            $mark = str_replace("\n", '', $row['mark']);
            $marks = array_filter(explode('[', $mark));
            foreach ($marks as $temp) {
                $data['authent_id'] = $row['id'];
                $data['user_id'] = $row['user_id'];
                $data['created_at'] = $row['created_at'];
                $data['updated_at'] = $row['updated_at'];
                if (strpos($temp, ']') !== false) {
                    $dd = explode(']', $temp);
                    if (count($dd) == 2) {
                        $data['updated_at'] = $data['created_at'] = strtotime($dd[0]);
                        $data['mark'] = $dd[1];
                    }
                } else {
                    $data['mark'] = $temp;
                }
                $items[] = $data;
            }
        }
        if (empty($items)) {
            return;
        }
        $connect->batchInsert('{{%user_authent_log}}', [
            'authent_id',
            'user_id',
            'created_at',
            'updated_at',
            'mark',
        ], $items)->execute();
    }

}
